from infra.handler import BaseHandler
from domain.activity.activity_db import get_activity_info
import json

class AddressHandler(BaseHandler):
    """
    地址相关接口
    """

    async def get(self):
        """
        获取地址信息
        支持通过activity_id参数获取活动地址
        """
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return
            
            activity_id = self.get_argument('activity_id', None)
            
            if activity_id:
                # 根据活动ID获取活动地址
                success, result = await get_activity_info(int(activity_id), user_id)
                
                if success:
                    address_info = result.get('address', {})
                    self.write(json.dumps({
                        "code": 200,
                        "msg": "获取活动地址成功",
                        "data": {
                            "address": address_info
                        }
                    }))
                else:
                    self.write(json.dumps({
                        "code": 404,
                        "msg": f"获取活动地址失败: {result}"
                    }))
            else:
                # 原有的获取地址列表功能
                self.write(json.dumps({
                    "code": 400,
                    "msg": "请提供activity_id参数"
                }))
                
        except Exception as e:
            self.write(json.dumps({
                "code": 500,
                "msg": str(e)
            }))

    def post(self):
        """
        新增地址
        """
        self.render_json()